//
//  SchStatisViewController.swift
//  BellManage
//
//  Created by Bestsch on 16/5/9.
//  Copyright © 2016年 wsl. All rights reserved.
//

import UIKit

class SchStatisViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {

    var tableView: UITableView!
    var SchArray = NSMutableArray()
    
    var pageIndex = 1
    
    var hud: MBProgressHUD!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.navigationItem.setNewTitle("学校详情")
        
        //1228 - 保存到本地数据进行读取
        self.SchArray = getLocationData(key: schStatisArray)
        
        InitViews()
    }
    
    func InitViews() {
        tableView = UITableView.init(frame: CGRect(x: 0, y: 0, width: screenW, height: screenH))
        tableView.backgroundColor = UIColor.init(hexString: "f6f6f6", alpha: 1)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = UITableViewCellSeparatorStyle.singleLine
        self.view.addSubview(tableView)
        setUpRefresh()
    }
    func setUpRefresh() {
        tableView.header = MJRefreshNormalHeader.init(refreshingTarget: self, refreshingAction: #selector(SchStatisViewController.getSchList))
        self.tableView.header.beginRefreshing()
    }
    /**
     获取已注册的学校
     */
    func getSchList() {
        let user = getUserPojo()
        let requestXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><rss version=\"2.0\"><channel><t>2</t><SuperType>\(user.SupperType!)</SuperType><UpperCode>\(user.UpperCode!)</UpperCode></channel></rss>"
        let url = server + superWebapp
        HttpPostUTF(url, requestXML: requestXml) { (data, result, error) in
            if error == nil {
                if result != "false" {
                    //1218 - 本地化
                    //++++++++++++++++++++++++++++++++++++++++
//                    self.SchArray = JsonFormt(str: result)
                    //++++++++++++++++++++++++++++++++++++++++
                    
                    setLocationData(result!, key: schStatisArray)
                    self.SchArray = getLocationData(key: schStatisArray)
                    
                    //++++++++++++++++++++
                }
                self.tableView.reloadData()
                self.tableView.header.endRefreshing()
            }else{
                let alert: UIAlertView = UIAlertView.init(title: "错误提示", message: error!.localizedDescription, delegate: nil, cancelButtonTitle: "知道了")
                alert.show()
                self.tableView.header.endRefreshing()
            }
        }
        
    }
    
    //貌似娇在更多没有用到
    
    func getMoreSch() {
        pageIndex += 1
        let page: String = String(pageIndex)
        let requestXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><rss version=\"2.0\"><t>2</t><status>2</status><type>2</type><top>20</top><pageindex>" + page + "</pageindex></rss>"
        let url = server + Statistics
        SchArray.addObjects(from: getData(url, request: requestXml) as [AnyObject])

        tableView.reloadData()
        tableView.footer.endRefreshing()
        
    }
    
    //MARK: - table view delegate and Data source
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 60
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return SchArray.count
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellIdentifier = "SchTableViewCellIdentifier";
        
        let cell: SchTableViewCell = SchTableViewCell.init(style: UITableViewCellStyle.default, reuseIdentifier: cellIdentifier)
        cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator
        cell.selectionStyle = UITableViewCellSelectionStyle.none;
        let dic = SchArray[indexPath.row] as! JSON
        let schName = dic["SchName"].stringValue
        cell.schName.text = schName
        
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        hud = MBProgressHUD.showAdded(to: self.view, animated: true)
        hud.mode = MBProgressHUDMode.indeterminate
        hud.labelText = "正在配置学校数据...请稍后"
        
        let queue = DispatchQueue(label: "queue")
        queue.async {
            
            let dic = self.SchArray[indexPath.row] as! JSON
            let schid = dic["SchSerID"].stringValue
            let schName = dic["SchName"].stringValue
            let UpSerID = dic["UpSerID"].stringValue
            
            let defaults = UserDefaults.standard
            
            defaults.set(schid, forKey: "schid")
            defaults.set(schName, forKey: "schname")
            defaults.set(UpSerID, forKey: "UpSerID")
            defaults.synchronize()
            let requestXML = "<?xml version=\"1.0\" encoding=\"utf-8\"?><rss version=\"2.0\"><channel><t>3</t><schid>\(schid)</schid></channel></rss>"
            let url = server + superWebapp
            
            initLocationData()
            HttpPostUTF(url, requestXML: requestXML, finished: { (data, result, error) in
                if error == nil {
                    if result == "false" {
                        let alert: UIAlertView = UIAlertView.init(title: "提示", message: "\(schName)尚未开通权限!", delegate: nil, cancelButtonTitle: "知道了")
                        alert.show()
                    }else {
                        
                        let array = JSON(data: (result?.data(using: String.Encoding.utf8))!)
                        if array.count > 0 {
                            
                            let rightArray = NSMutableArray(array: array.arrayObject!)
                            setRightArray(rightArray)
                        }
                        
                        //获取办公模块的信息
                        
                        #if HSSUPER || TXSUPER
                            
//                            let user = getUserPojo()
                            let officeUrl = server + adminofficewebappapi
                            let officeRequest = requestHeader + "1</t><schid>" + schid + "</schid><userid>" + UpSerID + "</userid><usertype>" + "" + "</usertype></channel></rss>"
                            HttpPostUTF(officeUrl, requestXML: officeRequest, finished: { (data, result, error) in
                                print("\(result!)")
                                if error == nil {
                                    let array = JSON(data: (result?.data(using: String.Encoding.utf8))!)
                                    let officeRightArray = NSMutableArray()
                                    
                                    if array.count != 0 {
                                        officeRightArray.addObjects(from: array.arrayObject!)
                                    }
                                    setOfficeRightArray(officeRightArray)
                                    
                                    let mainVC = ManagerTabbarViewController()
                                    self.present(mainVC, animated: false, completion: nil)
                                    
                                }else {
                                    UIAlertView.init(title: "错误提示", message: error?.localizedDescription, delegate: nil, cancelButtonTitle: "知道了").show()
                                }
                            })
                        #endif
                        
                        #if BELLSUPER
                            let mainVC = ManangeMainViewController()
                            
                            self.navigationController?.pushViewController(mainVC, animated: true)
                            
                        #endif
                    }
                    self.hud.hide(true)
                }else{
                    self.hud.hide(true)
                    let alert: UIAlertView = UIAlertView.init(title: "错误提示", message: error!.localizedDescription, delegate: nil, cancelButtonTitle: "知道了")
                    alert.show()
                }
            })

           
        }
        
    }
    

    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */
    
}
